#include <dd_context.h>
#include "dd_matrix.h"
#include <stdlib.h>
#include <stdio.h>
#include "dd_dynamic_array.h"

/* by default, graphics are drawn on the terminal, so creating a window
 * is not needed.
 * this function exist so it can be overriden with an "extention library"
 * that needs to create a new window
 * not sure if I keep this, still experimenting
 */
void dd_create_window() {

}

/* create context */
int dd_create_context() {

	/* allocate memory for screen's buffer (assume width and height
	 * are already set)
	 */
	dd_screen = malloc( sizeof(char) *(dd_swidth*dd_sheight) );

	/* error check */
	if (!dd_screen) {
		return 0;
	}

	/* create identity matrix */
	float mat[] = {	1, 0, 0, 0,
			0, 1, 0, 0,
			0, 0, 1, 0,
			0, 0, 0, 1};

	/* initialize global matrix, give it identity as first matrix */
	dd_cam = malloc( sizeof(struct dd_dynamic_array) );
	dd_da_init(dd_cam, sizeof(float[16]));
	dd_da_add(dd_cam, mat);

	return 0;
}

void dd_buffer_clear() {
	int i;
	for (i = 0; i < dd_h*dd_w; i++) {
		((char*) dd_screen)[i] = 0;
	}
}

void dd_buffer_draw() {
	/* clear terminal */
//	printf("\E[H\E[2J");

	/* for each pixel on buffer */
	int i;
	for (i = 0; i < dd_h*dd_w; i++) {
		if (i %dd_w == 0 && i != 0) {
			printf("\n");
		}
		
		int col = ((char*) dd_screen)[i];
		switch (col) {
			case 0:
			printf(" ");
			continue;
		}
	
		printf("%d", col);
	
	}
	
}

void dd_version() {
	printf("~~~ dd_core ~~~\n");
	printf("version: beta\n");
}

void dd_loop() {
	dd_create_context();
	while(1) {
		dd_update();
		dd_draw();
	}
}
